package com.sctvcloud.longchang.ui.activities;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.jiongbull.jlog.JLog;
import com.mob.tools.utils.DeviceHelper;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.sctvcloud.longchang.R;
import com.sctvcloud.longchang.application.Constances;
import com.sctvcloud.longchang.base.BaseActivity;
import com.sctvcloud.longchang.beans.SingleResult;
import com.sctvcloud.longchang.http.AbsNetCallBack;
import com.sctvcloud.longchang.http.DMethods;
import com.sctvcloud.longchang.http.NetUtils;
import com.sctvcloud.longchang.ui.scan.CaptureActivity;
import com.sctvcloud.longchang.ui.utils.KeyBoardUtils;
import com.sctvcloud.longchang.ui.utils.TitleUtils;
import com.sctvcloud.longchang.utils.UserManager;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 关于
 */
public class ScanActivity extends BaseActivity {
    @BindView(R.id.tv_scan)
    protected CustomFontTextView tv_scan;
    private static final int REQUEST_CODE_SCAN = 0x0000;// 扫描二维码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_scan);
        ButterKnife.bind(this);
    }
    @OnClick({R.id.tv_scan,R.id.title_top_back})
    protected void OnClick(View view) {
        if (view.getId() == R.id.tv_scan) {

            if (ContextCompat.checkSelfPermission(ScanActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(ScanActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
            } else {
                goScan();
            }

        }else if(view.getId() == R.id.title_top_back){
            finish();
        }
    }

    /**
     * 跳转到扫码界面扫码
     */
    private void goScan() {

        Intent intent = new Intent(this, CaptureActivity.class);
        intent.putExtra(UserAgreementActivity.RULE_TYPE,0);
        startActivityForResult(intent, REQUEST_CODE_SCAN);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    goScan();
                } else {
                    Toast.makeText(this, "你拒绝了权限申请，可能无法打开相机扫码哟！", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SCAN:// 二维码
                // 扫描二维码回传
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        //获取扫描结果
                        Bundle bundle = data.getExtras();
                        String result = bundle.getString(CaptureActivity.EXTRA_STRING);

                        upLoadInvitationCode(result);

                    }
                }
                break;
            default:
                break;
        }
    }



    /**
     * 提交邀请码
     *
     * @param code
     */
    private void upLoadInvitationCode(String code) {
        KeyBoardUtils.closeKeyboard(this);
        showProgress(getString(R.string.being_submit), false);
        ArrayMap<String, Object> map = new ArrayMap<>();
        if (code.endsWith("XO")) {
            if (null != UserManager.getInstance().getUser()) {
                //积分商城的邀请码
                map.put("inviteCode", code);
                map.put("userId", UserManager.getInstance().getUser().getPhoneNumber());
                map.put("token", UserManager.getInstance().getUser().getToken());
                NetUtils.getNetAdapter().checkInvitationCode(getOwnerName(), map, new AbsNetCallBack<SingleResult>(null) {
                    @Override
                    public void onSuc(SingleResult s) {
                        closeProgress();
                        if (s != null && s.isSuccess()) {
                            toast(getString(R.string.submit_success));
                            finish();
//                            addInvitation(Constances.ADD_INTEGRAL_INPUT_INVITATION, true);
                        } else {
                            toast(R.string.submit_failed);
                        }
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                        if (ex != null) {
                            ex.printStackTrace();
                        }
                        toast(TextUtils.isEmpty(errorMsg) ? "提交失败" : errorMsg);
                    }

                    @Override
                    public SingleResult doInBackground(SingleResult s) {
                        return super.doInBackground(s);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        closeProgress();
                    }
                });
            } else {
                toast("登录失效，请先登录");
            }
        } else {
            if (null != UserManager.getInstance().getUser()) {
                //市州推广邀请码
                String did =
                        DeviceHelper.getInstance(this).getDeviceId();
                if (TextUtils.isEmpty(did)) {
                    did = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
                }
                JLog.e("did=" + did);
                map.put("deviceId", did);
                map.put("inviteCode", code);
                map.put("userId", UserManager.getInstance().getUser().getPhoneNumber());
                map.put("siteId", Constances.SITE_ID);
                NetUtils.getNetAdapter().postGetSingle(getOwnerName(), DMethods.SendCode, map, new AbsNetCallBack<SingleResult>(null) {
                    @Override
                    public void onSuc(SingleResult s) {
                        closeProgress();
                        if (s != null && s.isSuccess()) {
                            toast(getString(R.string.submit_success));
                            finish();
//                        addInvitation(Constances.ADD_INTEGRAL_INPUT_INVITATION, true);

                        } else {
                            toast(R.string.submit_failed);
                        }
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                        if (ex != null) {
                            ex.printStackTrace();
                        }
                        toast(TextUtils.isEmpty(errorMsg) ? "提交失败" : errorMsg);
                    }

                    @Override
                    public SingleResult doInBackground(SingleResult s) {
                        return super.doInBackground(s);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        closeProgress();
                    }
                });
            } else {
                toast("登录失效，请先登录");
            }
        }
    }



}
